package org.zjt.io;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.Asserts;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;

/**
 * @author juntao.zhang
 * @version V1.0
 * @Description: TODO
 * @Package org.zjt.io
 * @date 2018/6/2 15:45
 */
@Slf4j
public class AIOTest {

    public static void main(String[] args) throws IOException, InterruptedException {

        Charset charset = Charset.defaultCharset();

        new Thread(()->{
            SocketAddress socketAddress = new InetSocketAddress(89);

            AsynchronousServerSocketChannel serverSock = null;
            try {
                serverSock = AsynchronousServerSocketChannel.open().bind(socketAddress);
            } catch (IOException e) {
                e.printStackTrace();
            }


            serverSock.accept(serverSock, new CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>() {

                /**
                 *
                 * @param sockChannel 请求端的channel
                 * @param serverSock  服务器的channel
                 */
                @Override
                public void completed(AsynchronousSocketChannel sockChannel, AsynchronousServerSocketChannel serverSock) {
                    serverSock.accept(serverSock, this);
                    sockChannel.write(charset.encode("zhangsan"));

                    //创建新的Buffer
                    ByteBuffer buffer = ByteBuffer.allocate(1024);


                    //异步读  第三个参数为接收消息回调的业务Handler
                    sockChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {

                        /**
                         * 异步读取
                         * @param result
                         * @param attachment
                         */
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                            log.info(String.valueOf(attachment));
                            attachment.flip();
                            log.info(charset.decode(attachment).toString());
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            log.error("attachment:{}",String.valueOf(attachment),exc);
                        }
                    });
                }

                @Override
                public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
                    exc.printStackTrace();
                }
            });
        }).start();

        Thread.sleep(300000);
    }
}
